package com.ccys.doctor.controller;

import cn.hutool.core.util.IdUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.doctor.doctorSetting.*;
import com.ccys.db.dto.doctor.patientHistory.DoctorPatientHistoryReadDto;
import com.ccys.db.entity.*;
import com.ccys.db.dto.doctor.doctorSetting.CheckUpdateClinicDto;
import com.ccys.db.dto.doctor.doctorSetting.CreateAcronymlistDto;
import com.ccys.db.dto.doctor.doctorSetting.DeleteAcronymDto;
import com.ccys.db.dto.doctor.doctorSetting.FavouritePrescriptionDto;
import com.ccys.db.dto.login.ForgotPasswordDto;
import com.ccys.db.entity.TblDoctorAcronyms;
import com.ccys.db.entity.TblFavouritePrescription;
import com.ccys.db.entity.TblFavouritePrescriptionDetail;
import com.ccys.db.mapper.TblDoctorSupportTabReadMapper;
import com.ccys.db.page.AppPageDto;
import com.ccys.db.vo.doctor.doctorSetting.*;
import com.ccys.doctor.service.*;
import com.github.pagehelper.PageInfo;
import com.google.api.client.util.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author：XLY
 * @Date：2024/2/5 0005
 */

@RestController
@RequestMapping("/doctorSetting")
@Api(tags = "Doctor Setting")
public class DoctorSettingController {


    @Resource
    private TblDoctorSupportTabReadMapper mapper;

    @Resource
    private DoctorAcronymsService acronymsService;

    @Resource
    private FavouritePrescriptionService favouritePrescriptionService;

    @Resource
    private FavouritePrescriptionDetailsService favouritePrescriptionDetailsService;

    @Resource
    private DoctorPcLoginService doctorPcLoginService;

    @Resource
    private TblDoctorSupportTabReadMapper doctorSupportTabReadMapper;

    @Resource
    private DoctorService doctorService;

    @Resource
    private PatientHistoryService patientHistoryService;

    @ApiOperation("Doctor Setting/ 1")
    @GetMapping("CheckShowAlterSupportTab")
    public ResponseResultApp CheckShowAlterSupportTab() {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        CheckShowAlterSupportTabVo res = mapper.checkShowAlterSupportTab(curLoginUserId);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Doctor Setting/ 2")
    @GetMapping("CheckUpdateClinic")
    public ResponseResultApp checkUpdateClinic(CheckUpdateClinicDto dto) {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        String doctorCountryOfResidence = dto.getDoctorCountryOfResidence();
        List<String> clinicIdList = mapper.checkUpdateClinicDto(curLoginUserId, doctorCountryOfResidence);
        List<Object> res = Lists.newArrayList();
        res.set(0, 0);
        res.set(1, 1);
        if (CollectionUtils.isNotEmpty(clinicIdList)) {
            int size = clinicIdList.size();
            res.add(size);
            if (size == 1) {
                res.add(clinicIdList.get(0));
            } else if (size > 1) {
                res.add(0);
            }
        }
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Doctor Setting/ 3")
    @PostMapping("CreateAcronymslist")
    @Transactional
    public ResponseResultApp createAcronymlist(@RequestBody CreateAcronymlistDto dto) {

        String curLoginUserGroupId = UserUtil.getCurLoginUserGroupId();
        String id = dto.getId();
        String acronym = dto.getAcronym();
        if (StringUtils.isEmpty(id)) {
            //根据acronym查询是否存在
            Integer count = mapper.checkAcronymsExist(acronym);
            if (count > 0) {
                return ResponseResultApp.error("Acronym already exist");
            }
        }
        TblDoctorAcronyms model = new TblDoctorAcronyms();
        model.setId(id);
        model.setDoctorId(dto.getDoctor_id());
        model.setStatus(dto.isStatus() ? 1 : 0);
        model.setAcronym(acronym);
        model.setIsDefault(Objects.isNull(dto.getIs_default()) ? 0 : dto.getIs_default());
        model.setGroupId(curLoginUserGroupId);
        model.setPhrase(dto.getPhrase());
        acronymsService.insertOrUpdate(model);

        //查询公共的和自己的返回
        acronymsService.getAcronyms(null, null);
        return ResponseResultApp.success();
    }


    @ApiOperation("Doctor Setting/ 4")
    @PostMapping("CreateOrUpdateFavouritePrescription")
    @Transactional
    public ResponseResultApp createOrUpdateFavouritePrescription(@RequestBody FavouritePrescriptionDto dto) {

        String id = dto.getId();
        if (StringUtils.isNotEmpty(id)) {
            //删除之前的details
            mapper.deleteFavouritePrescriptionDetail(id);
        }
        TblFavouritePrescription favouritePrescription = new TblFavouritePrescription();
        favouritePrescription.setId(id);
        String curLoginUserId = UserUtil.getCurLoginUserId();
        favouritePrescription.setDoctorId(curLoginUserId);
        favouritePrescription.setStatus(1);
        String groupId = UserUtil.getCurLoginUserGroupId();
        favouritePrescription.setGroupId(groupId);
        favouritePrescription.setIsDefault(0);
        favouritePrescription.setName(dto.getName());
        favouritePrescriptionService.insertOrUpdate(favouritePrescription);

        List<FavouritePrescriptionDto.PrescriptionVo> prescriptions = dto.getPrescriptions();
        if (CollectionUtils.isNotEmpty(prescriptions)) {

            List<TblFavouritePrescriptionDetail> collect = prescriptions.stream().map(x -> {
                TblFavouritePrescriptionDetail detail = new TblFavouritePrescriptionDetail();
                detail.setId(IdUtil.getSnowflakeNextIdStr());
                detail.setFavouritePrescriptionId(favouritePrescription.getId());
                detail.setAnyPrecautions(x.getAny_precautions());
                detail.setDosage(x.getDosage());
                detail.setCausesDrowsiness("true".equals(x.getCauses_drowsiness()) ? 1 : 0);
                detail.setDosageText(x.getDosage_text());
                detail.setPatientInstruction(x.getPatient_instruction());
                detail.setPharmacistInstruction(x.getPharmacist_instruction());
                detail.setPrice(x.getProduct_price());
                detail.setPrnReason(x.getPrn_reason());
                detail.setRemark(x.getRemark());
                detail.setProductId(x.getProduct_id());
                detail.setWhatIsFor(x.getWhat_is_for());
                return detail;
            }).collect(Collectors.toList());
            favouritePrescriptionDetailsService.insertAll(collect);
        }


        return ResponseResultApp.success();
    }


    @ApiOperation("Doctor Setting/ 5")
    @PostMapping("DeleteAcronymlist")
    @Transactional
    public ResponseResultApp deleteAcronymList(@RequestBody DeleteAcronymDto dto) {

        //删除原来的
        String id = dto.getId();
        if (StringUtils.isNotEmpty(id)) {
            mapper.deleteAcronym(id);
        }
        //  查询返回回去
        AcronymListVo res = acronymsService.getAcronyms(null, dto.getIs_default());
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Doctor Setting/ 6")
    @DeleteMapping("deleteFavouritePrescription")
    @Transactional
    public ResponseResultApp deleteFavouritePrescription(String favouritePrescriptionId) {

        //删除prescription
        mapper.deleteFavouritePrescription(favouritePrescriptionId);
        //删除detail
        mapper.deleteFavouritePrescriptionDetail(favouritePrescriptionId);

        return ResponseResultApp.success();
    }

    @ApiOperation("Doctor Setting/ 7")
    @DeleteMapping("ForgotPassword")
    @Transactional
    public ResponseResultApp forgotPassword(@RequestBody ForgotPasswordDto dto){
        return doctorPcLoginService.forgotPassword(dto);
    }

    @ApiOperation("Doctor Setting/ 8")
    @GetMapping("GetAcronyms")
    public ResponseResultApp<AcronymListVo> getAcronyms(String keyword, Integer is_default) {
        //  要分页
        AcronymListVo res = acronymsService.getAcronyms(keyword, is_default);
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Doctor Setting/ 9")
    @GetMapping("GetAcronymsByDoctorId")
    public ResponseResultApp<AcronymListVo> getAcronymsByDoctorId(String doctor_id){

        AcronymListVo res = acronymsService.getAcronymsByDoctorId(doctor_id);
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Doctor Setting/ 11")
    @GetMapping("GetCountryPlatformSetting")
    public ResponseResultApp<CountryPlatformSettingVo> getCountryPlatformSetting(String patient_country_of_residence) {
        //查询表 tbl_country
        CountryPlatformSettingVo res = mapper.getCountryPlatformSetting(patient_country_of_residence);
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Doctor Setting/ 12")
    @GetMapping("GetProfile")
    public ResponseResultApp<CountryPlatformSettingVo> getProfile() {
        return doctorService.getProfile();
    }

    @ApiOperation("Doctor Setting/ 13")
    @GetMapping("GetSupportTab")
    public ResponseResultApp<SupportTabResVo> getSupportTab() {

        List<SupportTabResVo.SupportTabVo> supportTab = mapper.getSupportTab();
        SupportTabResVo res = new SupportTabResVo();
        res.setSupportTabs(supportTab);
        return ResponseResultApp.success(res);

    }


    @ApiOperation("Doctor Setting/ 14")
    @GetMapping("GetSupportTabTitle")
    public ResponseResultApp<GetSupportTabTitleVo> getSupportTabTitle(String support_tab_id, String search_value) {
        // 要分页
        // is_read 的逻辑，根据当前登录人（doctorId）
        // 去查 tbl_Doctor_Support_Tab_Read ,如果这个tab_title_id存在，就代表已读
        // TODO: 2024/2/7 0007 search_value需要咨询安卓
        String curLoginUserId = UserUtil.getCurLoginUserId();
        AppPageDto.startPage();
        List<GetSupportTabTitleVo.TitleVo> supportTabTitle = mapper.getSupportTabTitle(curLoginUserId, support_tab_id);
        PageInfo<GetSupportTabTitleVo.TitleVo> info = new PageInfo<>(supportTabTitle);
        GetSupportTabTitleVo res = new GetSupportTabTitleVo();
        res.setTotalPage(info.getPages());
        res.setSupportTabTitles(supportTabTitle);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Doctor Setting/ 15")
    @PostMapping("GetUpdateReadSupportTabTitle")
    @Transactional
    public ResponseResultApp<UpdateReadSupportTabTitleVo> GetUpdateReadSupportTabTitle(@RequestBody UpdateReadSupportTabTitleDto dto) {

        TblDoctorSupportTabRead model = new TblDoctorSupportTabRead();
        model.setDoctorId(UserUtil.getCurLoginUserId());
        model.setSupportTabId(dto.getSupport_tab_id());
        model.setSupportTabTitleId(dto.getSupport_tab_title_id());
        int insert = doctorSupportTabReadMapper.insert(model);
        UpdateReadSupportTabTitleVo res = new UpdateReadSupportTabTitleVo();
        if (insert > 0) {
            res.setRead(true);
        }
        return ResponseResultApp.success(res);
    }



    @ApiOperation("Doctor Setting/ 16")
    @GetMapping("HandlePatientHistoryRead")
    public ResponseResultApp handlePatientHistoryRead(DoctorPatientHistoryReadDto dto){
        return patientHistoryService.handlePatientHistoryRead(dto);
    }


    @ApiOperation("Doctor Setting/ 17")
    @PostMapping("UpdateAcronymlist")
    @Transactional
    public ResponseResultApp<AcronymListVo> updateAcronymList(@RequestBody UpdateAcronymListDto dto) {

        //如果tbl_doctor_acronyms 的 is_default 是1代表后台设置的不能改
        String id = dto.getId();
        if (StringUtils.isNotEmpty(id)) {
            TblDoctorAcronyms entityById = acronymsService.findEntityById(id);
            if (Objects.nonNull(entityById)) {
                Integer isDefault = entityById.getIsDefault();
                if (isDefault == 1) {
                    return ResponseResultApp.success();
                }
            }
        }
        //insertOrUpdate
        TblDoctorAcronyms model = new TblDoctorAcronyms();
        model.setId(id);
        String doctor_id = dto.getDoctor_id();
        model.setDoctorId(StringUtils.isEmpty(doctor_id) ? UserUtil.getCurLoginUserId() : doctor_id);
        model.setDispOrder(dto.getDisp_order());
        model.setAcronym(dto.getAcronym());
        model.setPhrase(dto.getPhrase());
        model.setIsDefault(dto.getIs_default());
        model.setGroupId(UserUtil.getCurLoginUserGroupId());
        acronymsService.insertOrUpdate(model);
        //查询acronym返回回去
        AcronymListVo acronyms = acronymsService.getAcronyms(null, null);
        return ResponseResultApp.success(acronyms);
    }


    @ApiOperation("Doctor Setting/ 18")
    @PostMapping("UpdateDoctorAvailableStatus")
    @Transactional
    public ResponseResultApp updateDoctorAvailableStatus(@RequestBody DoctorAvailableStatusDto dto) {
        //查询有没有正在进行的consultation
        //有就返回信息：You should finish all your consultation before logging out

        //修改状态
        TblDoctor doctor = new TblDoctor();
        String curLoginUserId = UserUtil.getCurLoginUserId();
        doctor.setId(curLoginUserId);
        doctor.setOnlineStatus(dto.getStatus());
        doctorService.insertOrUpdate(doctor);
        return ResponseResultApp.success();
    }


    @ApiOperation("Doctor Setting/ 19")
    @PostMapping("UpdateDoctorStatus")
    @Transactional
    public ResponseResultApp updateDoctorStatus(@RequestBody DoctorAvailableStatusDto dto) {
        //    Update tbl_Doctor
        //    Set doctor_job_status = @PRM_doctor_status,
        //    doctor_job_sub_status = 0
        //    Where doctor_id = @PRM_doctor_id
        TblDoctor doctor = new TblDoctor();
        doctor.setJobStatus(dto.getStatus());
        doctor.setJobSubStatus(0);
        doctor.setId(UserUtil.getCurLoginUserId());
        doctorService.insertOrUpdate(doctor);
        return ResponseResultApp.success();
    }


    @ApiOperation("Doctor Setting/ 21")
    @PostMapping("UpdateSoundSetting")
    @Transactional
    public ResponseResultApp updateSoundSetting(@RequestBody SoundSettingDto dto) {

        //修改医生来电铃声设置，enable_sound,ringtone
        TblDoctor doctor = new TblDoctor();
        doctor.setId(UserUtil.getCurLoginUserId());
        doctor.setEnableSound(dto.is_enable_sound() ? 1 : 0);
        doctor.setRingtone(dto.getRingtone());
        doctorService.insertOrUpdate(doctor);
        //// TODO: 2024/2/7 0007 使用亚马逊上传接口把文字转换成语音上传
        //AmazonUploader amazonUploader = new AmazonUploader();
        //AmazonPolly amazonPolly = new AmazonPolly();
        //amazonPolly.TextToSpeech(model.ringtone, ConfigurationManager.AppSettings["UPLOAD_FOLDER"] + "\\" + doctor_id + ".mp3");
        //amazonUploader.deleteFile(Constants.S3_Folder.RINGTONE, doctor_id + ".mp3");
        //amazonUploader.UploadFileFromLocal(Constants.S3_Folder.RINGTONE, doctor_id + ".mp3", ConfigurationManager.AppSettings["UPLOAD_FOLDER"] + "\\" + doctor_id + ".mp3", true);

        return ResponseResultApp.success();
    }
}
